package edu.hawaii.halealohacli.command;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.resource.source.jaxb.Source;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 * Returns the energy consumption.
 * 
 * @author Yong Hong Hsu
 */
public class RankTowers implements Command {
  /**
   * Tests the ranking of towers based on their current energy consumption.
   * 
   * @param client a WattDepot client
   * @param source the source to query
   * @param days the first being the timestamp for the day to start at
   * @throws Exception on an error with the Server
   */
  @Override
  public void printResults(WattDepotClient client, Source source, XMLGregorianCalendar... days)
      throws Exception {

    if (client.isHealthy()) {
      System.out.format("Connected to server successfully.\n");
    }
    else {
      System.out.format("Could not connect to server.\n");
      return;
    }
    System.out.println("Rank Towers by Energy consumed, from " + days[0] + " to " + days[1]);
    HashMap<String, Double> map1 = new HashMap<String, Double>();
    List<Source> sources = client.getSources();
    XMLGregorianCalendar start = days[0];
    start.setTime(0, 0, 0);
    XMLGregorianCalendar end = days[1];
    end.setTime(0, 0, 0);

    for (int i = 0; i < sources.size(); i++) {
      if (!sources.get(i).getName().contains("-")) {
        map1.put(sources.get(i).getName(),
            client.getEnergyConsumed(sources.get(i).getName(), start, end, 60) / 1000);
      }
    }
    rankTow(map1.keySet(), map1.values());
  }

  /**
   * Sorts and prints the towers.
   * 
   * @param key the source name of client
   * @param value the energy consumed
   * @return sortedArray;
   */
  public Object[] rankTow(Set<String> key, Collection<Double> value) {
    List<String> mpKeys = new ArrayList<String>(key);
    List<Double> mpValues = new ArrayList<Double>(value);
    TreeSet<Double> sortedSet = new TreeSet<Double>(mpValues);
    Object[] sortedArray = sortedSet.toArray();
    int size = sortedArray.length;
    for (int i = 0; i < size; i++) {
      System.out.format("%20s      %s kWh%n", mpKeys.get(mpValues.indexOf(sortedArray[i])),
          sortedArray[i]);
    }
    return sortedArray;
  }
}
